<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Account;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Area;
use App\Models\Admin\Express;
use App\Models\Admin\Goods;
use App\Models\Admin\GoodsStore;
use App\Models\Admin\StockOrder;
use App\Models\Admin\StockOrderGoods;
use App\Models\Admin\Store;
use App\Models\Admin\StoreOrder;
use App\Models\Admin\StoreOrderGoods;
use App\Models\Api\Address;
use App\Models\Api\SalesStrategy;
use App\Tools\Financial;
use App\Tools\PrPdf;
use App\Tools\Prstatic;
use App\Tools\Texcel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    /**
     *发货订单
     */
    public function orderList()
    {
        $params = $this->requestArr;
        if ($params['export_excel'] == 1) {
            $list = StoreOrder::getPageList($params, 0);
            $title = '销售管理-出货订单';
//            $titleArr = ['编号', '旺店通订单编号', '代理商', '基本折扣', '商品数量', '商品总金额', '商品实付', '运费', '订单总金额', '收货人', '收货电话', '收货地址', '审核状态', '发货状态', '出库单号', '下单时间'];
            $titleArr = ['订单编号','出库单号', '旺店通订单编号', '代理商', '基本折扣', '商品数量', '商品总金额',  '运费', '订单总金额', '收货人', '收货电话', '收货地址', '审核状态', '发货状态', '快递单号', '下单时间'];
            $dataArr = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['order_sn'] = $item['order_sn'];
                $dataArr[$k]['stock_order_sn'] = $item['stock_order_sn'];
                $dataArr[$k]['src_order_no'] = $item['src_order_no'];
                $dataArr[$k]['store_name'] = $item['store_name'];
                $dataArr[$k]['discount_rate'] = $item['discount_rate'];
                $dataArr[$k]['total_number'] = $item['total_number'];
                $dataArr[$k]['goods_amount'] = $item['goods_amount'];
//                $dataArr[$k]['goods_pay_amount'] = $item['goods_pay_amount'];
                $dataArr[$k]['freight'] = $item['freight'];
                $dataArr[$k]['order_amount'] = $item['order_amount'];
                $dataArr[$k]['order_name'] = $item['order_name'];
                $dataArr[$k]['order_mobile'] = $item['order_mobile'];
                $dataArr[$k]['order_address'] = $item['order_province'] . '-' . $item['order_city'] . '-' . $item['order_area'] . '-' . $item['order_address'];
                $dataArr[$k]['order_status_name'] = $item['order_status_name'];
                $dataArr[$k]['send_status_name'] = $item['send_status_name'];
                $dataArr[$k]['tracking_number'] = $item['tracking_number'];
                $dataArr[$k]['created_at'] = $item['created_at'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }
        $list = StoreOrder::getPageList($params, $limit = 15);
        if (!empty($params['store_id'])) {
            $list->appends(['store_id' => $params['store_id']])->render();
        }
        if (!empty($params['order_sn'])) {
            $list->appends(['order_sn' => $params['order_sn']])->render();
        }
        if (!empty($params['stock_order_sn'])) {
            $list->appends(['stock_order_sn' => $params['stock_order_sn']])->render();
        }
        if (!empty($params['src_order_no'])) {
            $list->appends(['src_order_no' => $params['src_order_no']])->render();
        }
        if (!empty($params['tracking_number'])) {
            $list->appends(['tracking_number' => $params['tracking_number']])->render();
        }
        if (!empty($params['order_mobile'])) {
            $list->appends(['order_mobile' => $params['order_mobile']])->render();
        }
        if (!empty($params['start_time'])) {
            $list->appends(['start_time' => $params['start_time']])->render();
        }
        if (!empty($params['end_time'])) {
            $list->appends(['end_time' => $params['end_time']])->render();
        }
        $info['storeList'] = Store::getBaseList();
        $info['data'] = $list;
        return view('admin/order/orderList', $info);
    }

    // 订单PDF打印
    public function orderPdf()
    {
        $params = $this->requestArr;
        if ($params['id']) {
            $info = StoreOrder::getInfoById($params['id']);
            $goodsList = StoreOrderGoods::getListByOid($params['id']);
            $total = [];
            foreach ($goodsList as $item) {
                if ($item['is_give'] == 0) {
                    $total['goods_price_yu'] += $item['goods_price_yu'];
                    $total['goods_price_zn'] += $item['goods_price_yu'] * $item['goods_number'];
                }
                $total['num'] += $item['goods_number'];
            }

            // 获取快递公司信息
            $express = \App\Models\Api\Express::getAllList();
            $address = Address::getDefaultBySId($info['store_id']);

            // 调用 calculateFreightAndAmount 方法计算运费和订单金额
            $goods_info_arr = [];
            foreach ($goodsList as $item) {
                $goods_info_arr[] = [
                    'goods_id' => $item['goods_id'],
                    'goods_pid' => $item['goods_pid'],
                    'goods_num' => $item['goods_number'],
                    'goods_weight_m' => floatval($item['goods_weight_m'] ?? 1), // 补充商品毛重字段，默认值为1kg
                    'is_give' => $item['is_give'] ?? 0 // 补充是否赠品字段
                ];
            }
            $result = $this->calculateFreightAndAmount($goods_info_arr, $express[0], $address['province'],$info['store_id']);

            // 确保计算成功
            if (isset($result['error'])) {
                errorMsg($result['error']);
            }

            // 更新订单信息中的运费和总金额
            $info['freight'] = $result['freight'];
            $info['order_amount'] = $result['order_amount'];

            $storeInfo = Store::getInfoById($info['store_id']);
            $info['subsidiary'] = $storeInfo['subsidiary'] ?? "亿恩鑫（上海）生物科技有限公司";

            // 渲染视图并生成 PDF
            $html = view('admin/order/orderPdf', [
                'data' => $info,
                'storeInfo' => $storeInfo,
                'goodsList' => $goodsList,
                'total' => $total
            ])->render();

            $pdf = new PrPdf();
            return $pdf->makePdfByHtml($storeInfo['subsidiary'], $info['order_sn'], $html, 1);
        }
        errorMsg();
    }

    /**
     * 订单删除
     */
    public function orderDel()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if ($params['id']) {
                StoreOrder::where(['id' => $params['id']])->delete();
                StoreOrderGoods::where(['order_id' => $params['id']])->delete();
                successMsg();
            }
        }
        errorMsg();
    }

    /**
     * 修改订单信息
     */
    public function orderEdit()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if ($params['id']) {
                $info = StoreOrder::getInfoById($params['id']);
                $saveOrderAmount = $params['order_amount'];
                if ($info) {
                    if ($params['cancel']) {
                        StoreOrder::where(['id' => $params['id']])->update(['order_status' => 3, 'update_user' => $this->userArr['user_name']]);
                    } else {
                        if (!$params['goods']) {
                            errorMsg("请选择商品");
                        }
                        foreach ($params['goods'] as $goods) {
                            if (empty($goods['batch'])) {
                                errorMsg("请为所有商品选择入库批次");
                            }
                        }

                        // 获取当前订单所有商品记录

                        // 获取当前订单所有商品记录
                        $currentGoodsRecords = StoreOrderGoods::from('store_order_goods as sg')
                            ->select(['sg.*', 'g.goods_weight_m'])
                            ->leftJoin('goods as g', 'g.id', '=', 'sg.goods_id')
                            ->where('sg.order_id', $params['id'])
                            ->get()
                            ->keyBy('id');


                        $mergedGoods = [];
                        $totalPrice = 0;
                        $currentGoodsIds = [];
                        
                        foreach ($params['goods'] as $kk => $vv) {
                            $goodsIds = explode(',', $vv['goods_id']);
                            foreach ($goodsIds as $goodsId) {
                                $goodsId = trim($goodsId);
                                $key = "{$goodsId}_{$vv['is_give']}_" . $kk;
                                $mergedGoods[$key] = $vv;
                                $mergedGoods[$key]['goods_id'] = $goodsId;
                                $mergedGoods[$key]['goods_number'] = $vv['goods_number'];
                                $mergedGoods[$key]['goods_group'] = "";
                                // 判断是已有记录还是新记录
                                if (isset($currentGoodsRecords[$kk])) {
                                    // 已有记录，标记为更新
                                    $mergedGoods[$key]['is_update'] = true;
                                    $mergedGoods[$key]['record_id'] = $kk;
                                    // 从当前记录中获取 goods_weight_m
                                    $mergedGoods[$key]['goods_weight_m'] = $currentGoodsRecords[$kk]['goods_weight_m'];
                                    $mergedGoods[$key]['goods_group'] = $currentGoodsRecords[$kk]['goods_group'];
                                } else {
                                    // 新记录
                                    $mergedGoods[$key]['is_update'] = false;
                                    // 对于新记录，需要从商品表获取 goods_weight_m
                                    $goodsInfo = Goods::find($goodsId);
                                    $mergedGoods[$key]['goods_weight_m'] = $goodsInfo ? $goodsInfo->goods_weight_m : 0;
                                }
                                
                                // 计算非赠品商品的总价
                                if ($vv['is_give'] == 0) {
                                    $totalPrice += $vv['goods_price'] * $vv['goods_number'];
                                    $mergedGoods[$key]['goods_price'] = $vv['goods_price'];
                                } else {
                                    $mergedGoods[$key]['goods_price'] = 0;
                                }
                            }
                        }
                        
                        // 确保赠品价格为0
                        foreach ($mergedGoods as &$goods) {
                            if ($goods['is_give'] == 1) {
                                $goods['goods_price'] = 0;
                            }
                        }
                        unset($goods);

                        // 重新计算订单总金额
                        $params['order_amount'] = $totalPrice + ($params['freight'] ?? 0);
                        $params['goods_pay_amount'] = $params['order_amount'];
                        
                        // 检查库存
                        foreach ($mergedGoods as $goods) {
                            $goods_sale_num = Goods::where(['id' => $goods['goods_id']])->value('goods_sale_num');
                            if ($goods_sale_num < $goods['goods_number']) {
                                errorMsg("商品库存不足,商品ID:{$goods['goods_id']}");
                            }
                        }


                        // 组装商品信息
                        $goods_info_arr = [];
                        $goods_num = 0;
                        $goods_ids = [];
                        $goods_give_list = []; // 新增：赠品商品列表
                        foreach ($mergedGoods as $item) {
                            $goodsMum = $item['goods_number'];
                            // 根据is_give判断是普通商品还是赠品
                            if (isset($item['is_give']) && $item['is_give'] == 1) {
                                $goods_info_arr[] = [
                                    'goods_id' => $item['goods_id'],
                                    'type' => $item['type'],
                                    'goods_pid' => $item['goods_pid'],
                                    'goods_weight_m' => $item['goods_weight_m'],
                                    "goods_group" => $item['goods_group'],
                                    'goods_num' => $goodsMum,
                                    'is_give' => $item['is_give']
                                ];
                            } else {
                                $goods_info_arr[] = [
                                    'goods_id' => $item['goods_id'],
                                    'type' => $item['type'],
                                    'goods_pid' => $item['goods_pid'],
                                    "goods_group" => $item['goods_group'],
                                    'goods_weight_m' => $item['goods_weight_m'],
                                    'goods_num' => $goodsMum,
                                    'is_give' => $item['is_give']
                                ];
                            }
                        }

                        $cartArr = SalesStrategy::getAllGoodsList($info['store_id'], $goods_ids, $goods_num);
//                        # 地址物流信息
//                        $express = \App\Models\Api\Express::getAllList();
                        // 地址物流信息
                        $express = Express::getInfoById($info['express_id']);

                        if (!$express) {
                            errorMsg('快递公司不存在');
                        }
                        # 新的运费计算方式
                        if (!is_array($cartArr['goods_list']) || empty($cartArr['goods_list'])) {
                            $cartArr['goods_list'] = [];
                        }
                        $inputFreight = $params['freight'];
                        $result = $this->calculateFreightAndAmount($goods_info_arr, $express, $info['order_province'], $info['store_id']);
                        if (isset($result['error'])) {
                            errorMsg($result['error']);
                        }
                        // 商户余额验证
                        $is_storeYzMoney = Redis::GET('DEFAULT:storeYzMoney');
                        if ($is_storeYzMoney == 1) {
                            $storeMoney1 = Financial::getInfoByAid($info['store_id'], 1, 2, 'money');
                            $storeMoney2 = Financial::getInfoByAid($info['store_id'], 1, 1, 'money');
                            if (($params['order_amount']) > ($storeMoney1 + $storeMoney2)) {
                                errorMsg("商户余额不足，请进行充值");
                            }
                        }
                        $params['freight'] = $result['freight'];
                        // 如果order_amount_type=1，使用传入的order_amount，否则自动计算
                        if (isset($params['order_amount_type']) && $params['order_amount_type'] == 1) {
                            // 使用传入的订单金额
                            $params['goods_pay_amount'] = $saveOrderAmount;
                            $params['order_amount'] = $saveOrderAmount;
                            $params['goods_amount'] = $saveOrderAmount;
                            $totalPrice = $saveOrderAmount;
                            //freight_type =1 为指定运费
                            if (isset($params['freight_type']) && $params['freight_type'] == 1) {
                                $params['freight'] = $inputFreight;
                            }
                        } else {
                            // 自动计算订单金额
                            $params['order_amount'] = $result['order_amount'];
                            $params['goods_pay_amount'] = $result['order_amount'];
                            //freight_type =1 为指定运费
                            if (isset($params['freight_type']) && $params['freight_type'] == 1) {
                                $params['freight'] = $inputFreight;
                                $params['order_amount'] =  $result['order_amount'] - $result['freight'] + $inputFreight;
                            }
                        }
                        // 更新订单金额
                        $isOk = StoreOrder::editInfo($params);
                        if ($isOk) {
                            StoreOrder::where(['id' => $params['id']])->update([
                                'order_status' => 2,
                                'freight' => $params['freight'],
                                'send_status' => 1,
                                'update_user' => $this->userArr['user_name'],
                                'total_number' => array_sum(array_column($mergedGoods, 'goods_number')),
                                'goods_amount' => $totalPrice,
                                'order_amount' => $params['order_amount']
                            ]);
                            StoreOrder::successSend($params['id']);

                            // 处理商品记录
                            foreach ($mergedGoods as $goods) {
                                $updateInfo = [
                                    'goods_id' => $goods['goods_id'],
                                    "goods_group" => $goods['goods_group'],
                                    'goods_number' => $goods['goods_number'],
                                    'goods_price' => $goods['goods_price'],
                                    'goods_amount' => $goods['is_give'] == 0 ? $goods['goods_price'] * $goods['goods_number'] : 0,
                                    'is_give' => $goods['is_give'],
                                    'store_product_batch' => $goods['batch'] ?? '',
                                    'updated_at' => time(),
                                    'update_user' => $this->userArr['user_name'],
                                    'store_id' => $info['store_id'],
                                    'created_at' => time(),
                                    'create_user' => $this->userArr['user_name']
                                ];

                                if ($goods['is_update']) {
                                    // 更新已有记录
                                    StoreOrderGoods::where('id', $goods['record_id'])->update($updateInfo);
                                    $currentGoodsIds[] = $goods['record_id'];
                                } else {
                                    // 创建新记录
                                    $updateInfo['order_id'] = $params['id'];
                                    $newRecord = StoreOrderGoods::create($updateInfo);
                                    $currentGoodsIds[] = $newRecord->id;
                                }
                            }

                            // 删除已移除的记录
                            StoreOrderGoods::where('order_id', $params['id'])
                                ->whereNotIn('id', $currentGoodsIds)
                                ->delete();

                            $storeOrder = StoreOrder::getInfoById($params['id']);
                            $storeOrder['create_user'] = $this->userArr['user_name'];
                            StockOrder::outInfoByOrder($storeOrder);
                            $this->pushOrderToRedis($params['id'], $storeOrder['store_id']);
                        }
                    }
                    successMsg();
                }
            }
            errorMsg();
        } else {
            if ($params['id']) {
                $info = StoreOrder::getInfoById($params['id']);
                $infoArr['data'] = $info;
                $infoArr['goodsList'] = StoreOrderGoods::getListByOid($params['id']);
                $infoArr['repertoryList'] = GoodsStore::getRepertoryList($info['store_id']);
                foreach ($infoArr['repertoryList'] as &$goods) {
                    $batchList = DB::table('stock_order_goods as sog')
                        ->join('stock_order as so', 'sog.order_id', '=', 'so.id')
                        ->where('sog.goods_id', $goods['id'])
                        ->where('so.type', 2)
                        ->where('so.store_product_batch', '!=', '')
                        ->orderBy('so.store_product_batch', 'asc')
                        ->select('so.store_product_batch')
                        ->distinct()
                        ->get()
                        ->pluck('store_product_batch')
                        ->toArray();
                    $goods['batch_list'] = $batchList;
                }
                unset($goods);
                $infoArr['goodsListStr'] = json_encode($infoArr['repertoryList'], JSON_UNESCAPED_UNICODE);
                $infoArr['storeInfo'] = Store::getInfoById($info['store_id']);

                // 获取每个商品的批次信息
                $goodsBatchInfo = [];
                foreach ($infoArr['goodsList'] as &$goods) {
                    $batchList = DB::table('stock_order_goods as sog')
                        ->join('stock_order as so', 'sog.order_id', '=', 'so.id')
                        ->where('sog.goods_id', $goods['goods_id'])
                        ->where('so.type', 2) // 入库类型
                        ->where('so.store_product_batch', '!=', '')
                        ->whereNotNull('so.store_product_batch')
                        ->orderBy('so.store_product_batch', 'asc')
                        ->select('so.store_product_batch')
                        ->distinct()
                        ->get()
                        ->pluck('store_product_batch')
                        ->toArray();

                    // 确保批次号格式正确
                    $batchList = array_filter($batchList, function ($batch) {
                        return !empty($batch) && is_string($batch);
                    });

                    $goodsBatchInfo[$goods['goods_id']] = array_values($batchList); // 重新索引数组
                    $goods['store_product_batch'] = "-----";
                    // 如果未设置批次，默认取最老的
                    if (!empty($batchList)) {
                        $goods['store_product_batch'] = reset($batchList); // 取排序后的第一个元素
                    }
                }
                unset($goods);

                $infoArr['goodsBatchInfo'] = $goodsBatchInfo;
            }
            # 获取订单信息
            $store_id = $info['store_id'] ?? 0;
            # 购物车数据
            $goodsList = StoreOrderGoods::getListByOid($info['id']);
            $goods_ids = [];
            $goods_num = 0;
            // 组装商品信息
            $goods_info_arr = [];
            $goods_give_list = []; // 新增：赠品商品列表
            foreach ($goodsList as $item) {
                $goodsMum = $item['goods_number'];
                // 根据is_give判断是普通商品还是赠品
                if (isset($item['is_give']) && $item['is_give'] == 1) {
                    $goods_info_arr[] = [
                        'goods_id' => $item['goods_id'],
                        'type' => $item['type'],
                        'goods_pid' => $item['goods_pid'],
                        "goods_group" => $item['goods_group'],
                        'goods_weight_m' => $item['goods_weight_m'],
                        'goods_num' => $goodsMum,
                        'is_give' => $item['is_give']
                    ];
                } else {
                    $goods_info_arr[] = [
                        'goods_id' => $item['goods_id'],
                        'type' => $item['type'],
                        'goods_pid' => $item['goods_pid'],
                        "goods_group" => $item['goods_group'],
                        'goods_weight_m' => $item['goods_weight_m'],
                        'goods_num' => $goodsMum,
                        'is_give' => $item['is_give']
                    ];
                }
            }
            $cartArr = SalesStrategy::getAllGoodsList($store_id, $goods_ids, $goods_num);

            # 地址物流信息
            $express = \App\Models\Api\Express::getAllList();
            $address = Address::getDefaultBySId($store_id);

            $express_fee = 0;
            $result = $this->calculateFreightAndAmount($goods_info_arr, $express[0], $address['province'], $info['store_id']);
            if (isset($result['error'])) {
                errorMsg($result['error']);
            } else {
                $express_fee = $result['freight'];
            }
            foreach ($infoArr['goodsList'] as &$goods) {
                // 从result中查找对应goods_id的价格
                $goodsPrice = 0;
                foreach ($result['goods_list'] as $item) {
                    if ($item['goods_id'] == $goods['goods_id'] && $item['is_give'] == 0) {
                        $goodsPrice = $item['goods_price'];
                        break;
                    }
                }
                $goods['goods_price'] = $goodsPrice;
                if ($goods['type'] == 2 && $goods['goods_pid'] == 0) {
                    // 解析goods_group JSON数据
                    $goodsGroup = json_decode($goods['goods_group'], true);
                    if (is_array($goodsGroup)) {
                        // 为每个子商品设置goods_group_number
                        foreach ($goodsGroup as $groupItem) {
                            $childGoodsId = $groupItem['id'];
                            $childGoodsNumber = intval($groupItem['number']);
                            // 在goodsList中查找对应的子商品并设置goods_group_number
                            foreach ($infoArr['goodsList'] as &$childGoods) {
                                if ($childGoods['goods_id'] == $childGoodsId) {
                                    $childGoods['goods_group_number'] = $childGoodsNumber;
                                    break;
                                }
                            }
                        }
                    }

                    // 为没有设置goods_group_number的子商品设置默认值0
                    foreach ($infoArr['goodsList'] as &$childGoods) {
                        if (!isset($childGoods['goods_group_number'])) {
                            $childGoods['goods_group_number'] = 0;
                        }
                    }
                }
            }

            $infoArr['address'] = $address;
            $infoArr['express_id'] = $info['express_id'] ?? 0;
            $infoArr['express'] = $express;
            $infoArr['express_fee'] = $express_fee;
            $infoArr['orderStatus'] = Prstatic::$orderStatus;
            $infoArr['orderSendStatus'] = Prstatic::$orderSendStatus;
            $infoArr['data']['order_amount'] = $result['order_amount'];
            $infoArr['data']['total_number'] = $result['num'];
//            var_dump(json_encode($infoArr));die();
            if ($info['order_status'] != 2 && $info['send_status'] > 0) {
                //未发货 未审核
                return view('admin/order/orderEdit', $infoArr);
            } else {
                //未发货 已审核
                return view('admin/order/orderDetail', $infoArr);
            }
        }
    }


    /**
     * 计算运费和订单金额（可复用）
     * @param array $goods_info_arr 商品数组 [{good_id, num}]
     * @param array $express 已查到的快递公司信息
     * @param string $province 收货省份
     * @return array ['freight'=>..., 'order_amount'=>...]
     * Note:
     * - 赠品商品(is_give=1)不计入订单金额和运费计算
     * - 运费计算时跳过赠品商品的重量
     */
    private function calculateFreightAndAmount($goods_info_arr, $express, $province, $store_id)
    {
        if (empty($goods_info_arr) || !is_array($goods_info_arr)) {
            return ['error' => '商品数据异常'];
        }
        // 1. 计算总重量
        $sum_weight = 0;
        $goods_detail = [];
        foreach ($goods_info_arr as $item) {
            // 如果是赠送商品则不计算重量
//            if (isset($item['is_give']) && $item['is_give'] == 1) {
//                continue;
//            }
            $weight = floatval($item['goods_weight_m']) ?? 0; // 使用毛重字段goods_weight_m，单位kg
            $sum_weight += $weight * $item['goods_num'];
        }
        if ($sum_weight <= 0) {
            return ['error' => '商品重量异常'];
        }
        // 2. 查快递公司参数
        $area_list = $express['area_list'] ?? [];
        $first_unit = 0;
        $two_unit = 0;
        foreach ($area_list as $area) {
            if ($area['area_name'] == $province) {
                $first_unit = $area['first_unit'];
                $two_unit = $area['two_unit'];
                break;
            }
        }
        if ($first_unit === 0) {
            return ['error' => '未配置该省份运费'];
        }
        // 3. 运费计算
        $freight = $first_unit;
        if ($sum_weight > 1) {
            $extra_weight = ceil($sum_weight - 1); // 续重向上取整
            $freight += $extra_weight * $two_unit;
            // 顺丰加2元包装费
            if (strpos($express['express_name'], '顺丰') !== false) {
                $freight += 2;
            }
        }

        // 4. 订单金额计算
        $order_amount = 0;
        $goods_detail = [];
        // 收集组合商品的pid，避免重复计算子商品价格
        $combo_pids = [];
        foreach ($goods_info_arr as $item) {
            if (isset($item['goods_pid']) && $item['goods_pid'] != 0) {
                $combo_pids[] = $item['goods_pid'];
            }
        }
        $payGoodNum = 0;//商品数量
        foreach ($goods_info_arr as $key => $item) {
            $good_id = $item['goods_id'] ?? 0;
            $num = $item['goods_num'] ?? 0;
            $goods_pid = $item['goods_pid'] ?? 0;
            $is_give = $item['is_give'] ?? 0;
            $weight = floatval($item['goods_weight_m']) ?? 0;
            $type = $item['type'] ?? 1; // 默认为单品
            if (!$good_id || !$num) continue;
            $good = Goods::find($good_id);
            if ($is_give == 1) {
                $goods_detail[$key] = [
                    'goods_id' => $good_id,
                    'goods_pid' => $goods_pid,
                    'type' => $type,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => 0, // 赠品价格为0
                    'goods_num' => $num,
                    'goods_weight_m' => $weight,
                    'total_price' => 0,
                    'is_give' => 1 // 标记为赠品
                ];
                // 修改：赠品也需要计入商品数量
                $payGoodNum += $num;
                continue;
            }
            // 组合商品的子商品(goods_pid!=0)金额为0，仅做明细展示
            if ($goods_pid != 0) {
                $goodsInfo = GoodsStore::getOrderByGoodsId($store_id, $good_id, $num);
                $price = floatval($goodsInfo['sale_price']);
                $goods_detail[$key] = [
                    'goods_id' => $good_id,
                    'goods_pid' => $goods_pid,
                    'type' => $type,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => $price,
                    'goods_num' => $num,
                    'goods_weight_m' => $weight,
                    'total_price' => 0, // 子商品金额为0
                    'is_give' => 0
                ];
                // 修改：如果goods_pid不为0，说明是组合商品子项，需要计入商品数量
                $payGoodNum += $num;
                continue;
            }
            // 修改：type判断逻辑移除，直接累加单商品数量
            if ($item['type'] == 1) {
                $payGoodNum += $num;
            }
            // 单品或组合主商品正常累加金额
            $goodsInfo = GoodsStore::getOrderByGoodsId($store_id, $good_id, $num);
            $price = floatval($goodsInfo['sale_price']);
            // 如果是组合商品主项，使用组合商品价格；否则使用单品价格
            if ($type == 2 || in_array($good_id, $combo_pids)) {
                // 组合商品主项，使用主商品价格乘以数量作为总价
                $order_amount += $price * $num;
                $goods_detail[$key] = [
                    'goods_id' => $good_id,
                    'goods_pid' => $goods_pid,
                    'type' => $type,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => $price,
                    'goods_num' => $num,
                    'goods_weight_m' => $weight,
                    'total_price' => round($price * $num, 2),
                    'is_give' => 0, // 标记为非赠品
                    'is_combo_main' => 1 // 标记为组合商品主项
                ];
            } else {
                // 普通单品
                $order_amount += $price * $num;
                $goods_detail[$key] = [
                    'goods_id' => $good_id,
                    'goods_pid' => $goods_pid,
                    'type' => $type,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => $price,
                    'goods_num' => $num,
                    'goods_weight_m' => $weight,
                    'total_price' => round($price * $num, 2),
                    'is_give' => 0 // 标记为非赠品
                ];
            }

        }
        $order_amount += $freight;
        return ['goods_list' => $goods_detail, 'freight' => $freight, 'order_amount' => $order_amount,'num' => $payGoodNum];
    }


    /**
     * 动态获取运费
     */
    public function freightAndAmount()
    {
        $store_id = $this->requestArr['store_id'];
        $express_id = $this->requestArr['express_id'];
        $goods_info_arr_from_request = $this->requestArr['goods_info_arr'] ?? [];
        $province = $this->requestArr['province'] ?? '';
        $city = $this->requestArr['city'] ?? '';
        $area = $this->requestArr['area'] ?? '';
        $address = $this->requestArr['address'] ?? '';
        $total_weight = floatval($this->requestArr['total_weight'] ?? 0);
        $total_number = intval($this->requestArr['total_number'] ?? 0);

        // 组装商品信息
        $goods_info_arr = [];
        if (!empty($goods_info_arr_from_request)) {
            foreach ($goods_info_arr_from_request as $item) {
                $goods_id = $item['goods_id'] ?? 0;
                $goods_pid = $item['goods_pid'] ?? 0;
                $type = $item['type'] ?? 1;
                $goods_num = $item['goods_num'] ?? 0;
                $goods_weight_m = floatval($item['goods_weight_m'] ?? 1); // 默认1kg

                if ($goods_id && $goods_num >= 1) {
                    $goods_info_arr[] = [
                        'goods_id' => $goods_id,
                        'goods_pid' => $goods_pid,
                        'type' => $type,
                        'goods_num' => $goods_num,
                        'goods_weight_m' => $goods_weight_m,
                        'is_give' => $item['is_give'] ?? 0,
                    ];

                } else {
                    errorMsg('商品信息不完整或数量错误');
                }
            }
        }

        if (empty($goods_info_arr)) {
            errorMsg('缺少商品信息');
        }

        // 验证地址信息
        if (empty($province)) {
            errorMsg('请选择收货省份');
        }

        // 获取快递公司信息
        $express = Express::getInfoById($express_id);
        if (!$express) {
            errorMsg('快递公司不存在');
        }

        // 获取折扣
        $discount_rate = Store::where(['id' => $store_id])->value('discount_rate') ?? 1;
        // 调用统一计算逻辑
        $result = $this->calculateFreightAndAmount($goods_info_arr, $express, $province, $store_id);
        if (isset($result['error'])) {
            errorMsg($result['error']);
        }
        $order_amount = $result['order_amount'];
        $freight = $result['freight'];
        $goods_list = $result['goods_list'];
        $num = $result['num'];

        // 返回数据
        $info = [
            'goods_list' => $goods_list,
            'pay_num' => count(array_filter($goods_list, function($item) { return ($item['is_give'] ?? 0) == 0; })),
            'num' => $num,
            'goods_money' => round($order_amount, 2),
            'total_money' => round($order_amount, 2),
            'express' => Express::getAllList(),
            'address' => [
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'address' => $address
            ],
            'express_fee' => round($freight, 2),
            'discount_rate' => $discount_rate,
            'hk_money' => Financial::getInfoByAid($store_id, 1, 1, 'money'),
            'gl_money' => Financial::getInfoByAid($store_id, 1, 2, 'money')
        ];

        successMsg($info);
    }


    /**
     * 根据商品列表、快递、省份，计算金额与运费
     * @param array $goods_list [{goods_id, goods_num, is_give?}]
     * @param array $express 快递信息（含 area_list）
     * @param string $province 收货省
     * @param integer $store_id 商家id
     * @return array ['goods_list' => [...], 'order_amount' => ..., 'freight' => ..., 'original_amount' => ...]
     */
    private function calcAmountByGoodsList($goods_list, $express, $province, $store_id)
    {
        $sum_weight = 0;
        $goods_detail = [];
        $order_amount = 0; // 折扣后总金额
        $original_amount = 0; // 折扣前总金额

        // 验证输入参数
        if (empty($goods_list) || !is_array($goods_list)) {
            return ['error' => '商品列表不能为空'];
        }

        foreach ($goods_list as $item) {
            // 参数校验
            $good_id = $item['goods_id'] ?? 0;
            $num = $item['goods_num'] ?? 0;
            if (!$good_id || !$num) continue;

            $good = \App\Models\Admin\Goods::find($good_id);
            if (!$good) continue;

            $goodsInfo = GoodsStore::getOrderByGoodsId($store_id, $good_id, $num);
            $price = floatval($goodsInfo['sale_price']);
            $goods_detail['goods_price'] = $price;
            $weight = floatval($good['goods_weight_m']);
            $is_give = $item['is_give'] ?? 0;
            // 赠品处理
            if ($is_give == 1) {
                $goods_detail[] = [
                    'goods_id' => $good_id,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => 0,
                    'goods_num' => $num,
                    'goods_weight_m' => $weight,
                    'total_price' => 0,
                    'is_give' => 1
                ];
                continue;
            }

            // 金额计算
            $original_item_total_price = $price * $num; //商品金额*商品数量
//            $discounted_item_total_price = $original_item_total_price * $discount_rate; //商品金额*商品数量 *折扣率

            // 累计计算
            $sum_weight += $weight * $num;
            $order_amount += $original_item_total_price;

            $goods_detail[] = [
                'goods_id' => $good_id,
                'goods_name' => $good['goods_name'],
                'goods_price' => $price,
                'goods_num' => $num,
                'goods_weight_m' => $weight,
                'total_price' => round($original_item_total_price, 2),
                'is_give' => 0
            ];
        }

        // 重量验证
        if ($sum_weight <= 0) {
            return ['error' => '商品重量异常'];
        }

        // 运费计算
        $area_list = $express['area_list'] ?? [];
        $first_unit = 0;
        $two_unit = 0;

        foreach ($area_list as $area) {
            if ($area['area_name'] == $province) {
                $first_unit = $area['first_unit'];
                $two_unit = $area['two_unit'];
                break;
            }
        }

        if ($first_unit === 0) {
            return ['error' => '未配置该省份运费'];
        }

        $freight = $first_unit;
        if ($sum_weight > 1) {
            $extra_weight = ceil($sum_weight - 1);
            $freight += $extra_weight * $two_unit;
            // 顺丰特殊处理
            if (strpos($express['express_name'], '顺丰') !== false) {
                $freight += 2;
            }
        }

        // 最终金额计算（四舍五入保留2位小数）
        return [
            'goods_list' => $goods_detail,
            'freight' => round($freight, 2),
            'order_amount' => round($order_amount, 2), // 折扣后商品总价
            'original_amount' => round($order_amount + $freight, 2), // 折扣前商品总价 + 运费
        ];
    }

    /**
     * 简化版本：调用统一运费和金额计算逻辑
     * @param array $goods_info_arr 商品数组 [{good_id, num}]
     * @param array $expressList 当前快递公司信息
     * @param string $province 省份
     * @param int $expressId 快递ID
     * @return array ['freight'=>..., 'order_amount'=>...]
     */
    private function oneFreightAndAmount($goods_info_arr, $expressList, $province, $expressId, $store_id)
    {
        // 整理为 calcAmountByGoodsList 的格式
        $formatted_goods_list = array_map(function($item) {
            return [
                'goods_id' => $item['goods_id'] ?? $item['good_id'] ?? 0,
                'goods_num' => $item['goods_num'] ?? $item['num'] ?? 0
            ];
        }, $goods_info_arr);

        // 调用统一计算方法
        $result = $this->calcAmountByGoodsList($formatted_goods_list, $expressList, $province,$store_id);

        if (isset($result['error'])) {
            return ['error' => $result['error']];
        }

        return [
            'freight' => $result['freight'],
            'order_amount' => $result['order_amount']
        ];
    }


    /**
     * 将订单数据写入Redis队列
     * @param int $order_id 订单ID
     * @param int $store_id 店铺ID
     * @return bool
     */
    private function pushOrderToRedis($order_id, $store_id)
    {
        try {
            // 获取订单详情
            $orderInfo = StoreOrder::getInfoById($order_id);
            $goodsList = StoreOrderGoods::getListByOid($order_id, 1);
            $goodsListJson = json_encode($goodsList, JSON_UNESCAPED_UNICODE);
            Log::info('pushOrderToRedis goodsListJson', [$goodsListJson]);
            $storeInfo = Store::find($store_id);
            //物流方式 圆通/中通5 顺丰8
            $logisticsType = 5;
            if ($orderInfo['express_id'] == 1) {
                $logisticsType = 5; //圆通/中通
            } elseif ($orderInfo['express_id'] == 2) {
                $logisticsType = 8; //顺丰速运
            } elseif ($orderInfo['express_id'] == 3) {
                $logisticsType = 88; //德邦
            }

            $order_time = date('Y-m-d H:i:s',$orderInfo['order_time']);

            $amountMoney = 0;
            // 构建旺店通订单数据
            $trade_list = [
                [
                    'tid' => $orderInfo['order_sn'], // 原始单号
                    'trade_status' => 30, // 30 待发货状态 50已发货(平台销售订单已经发货时推送此状态)，如果已发货在自建商城代表订单完结状态，无后续状态变更，直接推送状态值70。
                    'delivery_term' => 1, // 款到发货
                    'pay_status' => 2, // 已付款
                    'trade_time' => $order_time,
                    'pay_time' => $order_time,
                    'buyer_nick' => $storeInfo->store_name, // 客户网名
                    'receiver_name' => $orderInfo['order_name'],
                    'receiver_mobile' => $orderInfo['order_mobile'],
                    'receiver_province' => $orderInfo['order_province'],
                    'receiver_city' => $orderInfo['order_city'],
                    'receiver_district' => $orderInfo['order_area'],
                    'receiver_address' => $orderInfo['order_address'],
                    'logistics_type' => $logisticsType, // 物流方式 圆通/中通5 顺丰8 德邦88
                    'invoice_kind' => 0, // 不需要发票
                    'post_amount' => $orderInfo['freight'], // 邮费
//                    'paid' => $orderInfo['goods_amount']+$orderInfo['freight'], // 已付金额
                    'paid' => $orderInfo['freight'], // 已付金额
                    'cod_amount' => 0,
                    'ext_cod_fee' => 0,
                    'other_amount' => 0,
                    'order_list' => []
                ]
            ];

            // 处理商品数据，合并相同商品ID的记录
            $processedGoodsList = [];
            foreach ($goodsList as $goods) {
                // 使用goods_id和is_give组合作为唯一键
                $key = $goods['goods_id'];
                if (!isset($processedGoodsList[$key])) {
                    $processedGoodsList[$key] = $goods;
                } else {
                    // 累加商品数量和总金额
                    $processedGoodsList[$key]['goods_number'] += $goods['goods_number'];
                    $processedGoodsList[$key]['goods_amount'] += $goods['goods_amount'];

                    // 如果当前记录不是赠品而原记录是赠品，则替换价格
                    if ($goods['is_give'] == 0 && $processedGoodsList[$key]['is_give'] == 1) {
                        $processedGoodsList[$key]['goods_price'] = $goods['goods_price'];
                        $processedGoodsList[$key]['is_give'] = 0;
                    }
                }
            }
            $processedGoodsListJson = json_encode($processedGoodsList, JSON_UNESCAPED_UNICODE);
            Log::info('pushOrderToRedis processedGoodsList', [$processedGoodsListJson]);

            // 重新索引数组
            $processedGoodsList = array_values($processedGoodsList);
            // 构建订单商品列表
            foreach ($processedGoodsList as $goods) {
                // 兜底查商品表
                if (empty($goods['goods_sn'])) {
                    $goodsInfo = Goods::find($goods['goods_id']);
                    if ($goodsInfo) {
                        if (empty($goods['goods_sn'])) $goods['goods_sn'] = $goodsInfo->goods_sn;
                    }
                }
                // goods_no和spec_no不能同时为空
                if (empty($goods['goods_sn'])) {
                    continue; // 跳过这个商品，或者报错
                }
//                $goods_price = $goods['goods_price_yu'] ?? 0;
//                if ($goods['is_give'] == 1) {
//                    $goods_price =  0;
//                }
                $goods_price = 0;
                $amountMoney += $goods_price * $goods['goods_number'];

                $trade_list[0]['order_list'][] = [
                    'oid' => $orderInfo['order_sn'] . time().$goods['goods_id'],
                    'status' => 30,
                    'refund_status' => 0,
                    'goods_id' => $goods['goods_id'],
                    'spec_id' => $goods['spec_id'] ?? '',
                    'goods_no' => $goods['goods_sn'] ?? '',
                    'spec_no' => $goods['goods_sn']. "_" . $goods['goods_unit'] . "_" . $goods['goods_specification'] ?? '', // spec_no优先，没有就用goods_sn兜底 规格编码
                    'goods_name' => $goods['goods_name'],
                    'spec_name' => $goods['goods_specification'] ?? '',//平台规格名称
                    'num' => $goods['goods_number'],
                    'price' => $goods_price,
                    'adjust_amount' => 0,
                    'discount' => 0,
                    'share_discount' => 0,
                    'cid' => $goods['cate_id'] ?? ''
                ];

            }

            $trade_list[0]['paid'] =  $amountMoney +$orderInfo['freight']; // 已付金额 订单总金额+运费
            // 将订单数据写入Redis队列
            $pushJson = json_encode(['trade' => $trade_list[0], 'order_list' => $trade_list[0]['order_list']], JSON_UNESCAPED_UNICODE);
            Log::info('后台订单写入Redis队列数据', [$pushJson]);
            Redis::rpush('order:pending:push', $pushJson);

            return true;
        } catch (\Exception $e) {
            Log::error('后台订单写入Redis队列失败', [
                'order_id' => $order_id,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * 快递公司列表
     */
    public function expressList()
    {
        $params = $this->requestArr;
        if ($params['export_excel'] == 1) {
            $list = Express::getPageList($params, 0);
            $title = '销售管理-运费设置';
            $titleArr = ['快递', '运费', '订单满减', '备注', '添加时间'];
            $dataArr = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['express_name'] = $item['express_name'];
                $dataArr[$k]['money'] = $item['money'];
                $dataArr[$k]['order_money'] = $item['order_money'];
                $dataArr[$k]['remark'] = $item['remark'];
                $dataArr[$k]['status'] = $item['status'];
                $dataArr[$k]['created_at'] = $item['created_at'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }
        $list = Express::getPageList($params, $limit = 15);
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        return view('admin/order/expressList', ['data' => $list]);
    }

    /**
     * 修改快递
     */
    public function expressEdit()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if (!$params['express_name']) {
                errorMsg('请填写快递名');
            }
            Express::addOrUpInfo($params);
            successMsg();
        } else {
            if ($params['id']) {
                $info = Express::getInfoById($params['id']);
            } else {
                $info['area_list'] = Area::getProvinceByExpress();
            }
            $statusList = Prstatic::$status;
            return view('admin/order/expressEdit', ['data' => $info, 'statusList' => $statusList]);
        }
    }

    /**
     * 设置收费限制
     */
    public function storeYzMoney()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            $is_storeYzMoney = Redis::GET('DEFAULT:storeYzMoney') ? 0 : 1;
            if ($is_storeYzMoney == 1) {
                Account::where(['account_cate' => 1])->update(['money' => 0]);
            }
            $is = Redis::SET('DEFAULT:storeYzMoney', $is_storeYzMoney);
            successMsg();
        } else {
            $is_storeYzMoney = Redis::GET('DEFAULT:storeYzMoney') ?: 0;

            return view('admin/order/storeYzMoney', ['is_storeYzMoney' => $is_storeYzMoney]);
        }
    }

    /**
     * 前端传入 order_sn 和 goods_info_arr（包含商品ID和数量）。
     * 后端通过订单号查找订单，获取快递ID和收货省份。
     * 循环商品信息，查找每个商品的净重（goods_weight_j），乘以数量累加得到总重量。
     * 查找快递公司参数，获取首重和续重价格。
     * 运费计算：
     * 首重1kg按首重价
     * 超过1kg部分，续重向上取整，每1kg加一次续重价
     * 顺丰有续重时加2元包装费
     * 返回运费
     * 计算订单金额：
     * 所有已选商品的价格之和加上运费
     */
    public function calcAmount()
    {
        $params = request()->all();
        $order_sn = $params['order_sn'] ?? null;
        $goods_info_arr = $params['goods_info_arr'] ?? [];
        if (!$order_sn || empty($goods_info_arr)) {
            return response()->json(['code' => 0, 'msg' => '参数缺失']);
        }
        // 1. 通过订单号查找订单信息
        $order = \App\Models\Admin\StoreOrder::where(['order_sn' => $order_sn])->first();
        if (!$order) {
            return response()->json(['code' => 0, 'msg' => '订单不存在']);
        }
        $express_id = $order['express_id'];
        $province = $order['order_province'];
        // 2. 计算总重量
        $sum_weight = 0;
        foreach ($goods_info_arr as $item) {
            $good_id = $item['good_id'] ?? 0;
            $num = $item['num'] ?? 0;
            if (!$good_id || !$num) continue;
            $good = \App\Models\Admin\Goods::find($good_id);
            $weight = $good ? floatval($good['goods_weight_m']) : 0; // 使用毛重字段goods_weight_m，单位kg
            $sum_weight += $weight * $num;
        }
        if ($sum_weight <= 0) {
            return response()->json(['code' => 0, 'msg' => '商品重量异常']);
        }
        // 3. 查快递公司参数
        $express = Express::getInfoById($express_id);
        if (!$express) {
            return response()->json(['code' => 0, 'msg' => '快递公司不存在']);
        }
        $area_list = $express['area_list'] ?? [];
        $first_unit = 0;
        $two_unit = 0;
        foreach ($area_list as $area) {
            if ($area['area_name'] == $province) {
                $first_unit = $area['first_unit'];
                $two_unit = $area['two_unit'];
                break;
            }
        }
        if ($first_unit === 0) {
            return response()->json(['code' => 0, 'msg' => '未配置该省份运费']);
        }
        // 4. 运费计算
        $freight = $first_unit;
        if ($sum_weight > 1) {
            $extra_weight = ceil($sum_weight - 1); // 续重向上取整
            $freight += $extra_weight * $two_unit;
            // 顺丰加2元包装费
            if (strpos($express['express_name'], '顺丰') !== false) {
                $freight += 2;
            }
        }
        // 5. 订单金额计算
        $order_amount = 0;
        $store_id = $order['store_id'];
        if (empty($store_id)) {
            return response()->json(['code' => 0, 'msg' => '订单查询失败']);
        }
        $discount_rate = \App\Models\Admin\Store::where(['id' => $store_id])->value('discount_rate') ?? 1;

        if (empty($discount_rate)) {
            return response()->json(['code' => 0, 'msg' => '折扣率不存在']);
        }
        foreach ($goods_info_arr as $item) {
            $good_id = $item['good_id'] ?? 0;
            $num = $item['num'] ?? 0;
            if (!$good_id || !$num) continue;
            $good = \App\Models\Admin\Goods::find($good_id);
            $price = $good ? floatval($good['goods_price']) : 0;
            $order_amount += $price * $num * $discount_rate; // 应用折扣率
        }
        $order_amount += $freight;
        return response()->json(['code' => 1, 'data' => ['freight' => $freight, 'order_amount' => $order_amount]]);
    }

}
